/**
 * 
 */
package com.android.whereismy;

import java.util.List;
import java.util.Map;

import android.app.ProgressDialog;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.android.whereismy.mail.MailControler;
import com.android.whereismy.util.CmnConsts;
import com.android.whereismy.util.CmnUtils;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

/**
 * @author akarae
 *
 */
public class Unit extends MapActivity {

    MapView mapView;
    MapController mapControl;
    LocationManager locationMgr;
    Criteria criteria;
    Location myLocation;
    GeoPoint targetGeoPoint;
    MyLocationOverlay locationOverlay;
    
    Boolean isMobileCon = false;
    Boolean isWifiCon = false;
    Boolean isNetworkLocationActivated = false;
    Boolean isGpsLocationActivated = false;
    
    int intLat;
    int intLong;
    String bestProvider;
    String strUnitId;
    String strAuthKey;
    Boolean mailFlg = false;
    
    private ProgressDialog pd;
    
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.unit);

        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(false);
        
        mapControl = mapView.getController();
        mapControl.setZoom(17);
        
        // set-up LocationManager
        setUpLocation();

        // get current location
        getCurrentLocation();

        // animate to location
        moveOn();

        setOverlay();
        
        // submit button
        final Button button_report = (Button) findViewById(R.id.button_report);
        button_report.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                
                EditText textUnitId = (EditText) findViewById(R.id.EditUnitId);
                EditText textAuthKey = (EditText) findViewById(R.id.EditAuthKey);
                
                strUnitId = textUnitId.getText().toString();
                strAuthKey = CmnUtils.getMd5Hash(textAuthKey.getText().toString());
                
                if (CmnUtils.isStrEmpty(strUnitId)) {
                    Toast.makeText(Unit.this, "input UnitID", Toast.LENGTH_LONG).show();
                    return;
                }
                
                sendReport();
            }
        });
        
        // clear button
        final Button button_clear = (Button) findViewById(R.id.button_clear);
        button_clear.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                EditText textUnitId = (EditText) findViewById(R.id.EditUnitId);
                EditText textAuthKey = (EditText) findViewById(R.id.EditAuthKey);
                
                // reset EditText to null
                textUnitId.setText(null);
                textAuthKey.setText(null);
            }
        });

        // current_location button
        final Button button_cur_location = (Button) findViewById(R.id.button_my_location);
        button_cur_location.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                getCurrentLocation();
                moveOn();
            }
        });
    }
    
    @Override
    public void onStart() {
        super.onStart();
    }
    
    /**
     * set-up related to LBS
     */
    public void setUpLocation() {
        locationMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        criteria.setAccuracy(Criteria.NO_REQUIREMENT);
        criteria.setPowerRequirement(Criteria.NO_REQUIREMENT);
    }
    
    /**
     * get current location(by best provider)
     */
    public void getCurrentLocation() {
        bestProvider = locationMgr.getBestProvider(criteria, true);
        locationMgr.requestLocationUpdates(bestProvider, 5000, 1, locationListener);
        myLocation = locationMgr.getLastKnownLocation(bestProvider);
        intLat = (int) (myLocation.getLatitude() * 1E6);
        intLong = (int) (myLocation.getLongitude() * 1E6);
        targetGeoPoint = new GeoPoint(intLat, intLong);
    }

    protected void setOverlay() {
        
        // Add the MyPositionOverlay
        locationOverlay = new MyLocationOverlay(myLocation, bestProvider);
        List<Overlay> overlays = mapView.getOverlays();
        overlays.add(0, locationOverlay);
    }
    
    /**
     * move the map to indicated location.
     */
    public void moveOn() {
        mapControl.animateTo(targetGeoPoint);
        mapControl.setCenter(targetGeoPoint);
    }
    
    private final LocationListener locationListener = new LocationListener() {
        // when location updated
        public void onLocationChanged(Location location) {
            myLocation = location;
        }
        
        public void onProviderDisabled(String provider) {
            // TODO when provider will be changed to Disabled
            
        }
        
        public void onProviderEnabled(String provider) {
            // TODO when provider will be changed to Enabled
            
        }
        
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // if status is AVAILABLE
            if (status == 2) {
                bestProvider = provider;
            }
        }
    };
    
    protected void getSystemInfo() {

        Map<String, Boolean> comStatMap = CmnUtils.getComInfo((ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE));
        
        if (comStatMap.get(CmnConsts.MOBILE_STAT)) {
        } else {
        }
        if (comStatMap.get(CmnConsts.MOBILE_CON)) {
            isMobileCon = true;
        } else {
            isMobileCon = false;
        }
        
        if (comStatMap.get(CmnConsts.WIFI_STAT)) {
        } else {
        }
        if (comStatMap.get(CmnConsts.WIFI_STAT)) {
            isWifiCon = true;
        } else {
            isWifiCon = false;
        }
        
        Map<String, Boolean> locStatMap = CmnUtils.getLocInfo((LocationManager) getSystemService(Context.LOCATION_SERVICE));
        if (locStatMap.get(CmnConsts.GPS_STAT)) {
            isNetworkLocationActivated = true;
        } else {
            isNetworkLocationActivated = false;
        }
        if (locStatMap.get(CmnConsts.NETWORK_STAT)) {
            isGpsLocationActivated = true;
        } else {
            isGpsLocationActivated = false;
        }
    }
    public void sendReport() {
        pd = ProgressDialog.show(this, CmnConsts.PRC_TITLE, CmnConsts.PRC_REPORT, true, false);
        Thread thread = new Thread(new Runnable() {
                  public void run() {
                      
                      MailControler mc = new MailControler(getResources());
                      
                      try {
                          // send a mail
                          mc.sendMail(
                                  strUnitId, 
                                  strAuthKey, 
                                  String.valueOf(mapView.getMapCenter().getLatitudeE6()), 
                                  String.valueOf(mapView.getMapCenter().getLongitudeE6()),
                                  bestProvider);
                      } catch (Exception e) {
                          Log.d(CmnConsts.DEBUG_TAG, "report failed");
                          mailFlg = false;
                      }
                      mailFlg = true;
                      handler.sendEmptyMessage(0);
                  }
        });
        thread.start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            pd.dismiss();
            if (mailFlg) {
                Toast.makeText(Unit.this, "report completed", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(Unit.this, "report failed", Toast.LENGTH_LONG).show();
            }
        }
    };
}
